import { useSelector } from 'react-redux';
import { useHistory } from 'react-router-dom';

import { TOTAL_QUESTION } from '../../../../constants/app-constants';
/**
 * 判断用户是否跳题
 */
export const useCheckMissedQuestion = (
  questionnaireUuid: string,
  currentQuestionIndex: number,
) => {
  const history = useHistory();
  const { scoreList } = useSelector((
    storeState: QA.ReduxState
  ) => ({
    scoreList: storeState.scoreList
  }));

  for (let i = 0; i < currentQuestionIndex; i += 1) {
    if (scoreList[i] === undefined) {
      history.push(`/questionAnswer/home/${questionnaireUuid}/question/${i}`);
      break;
    }
  }
};

/**
 * 判断路由是否在允许范围内
 */
export const useCheckQuestionRange = (
  currentQuestionIndex: number,
  questionnaireUuid: string
) => {
  const history = useHistory();
  // 显示题目的路由范围
  const isInQuestionRange = (currentQuestionIndex >= 0)
    && (currentQuestionIndex < TOTAL_QUESTION);
  // 超出路由范围或者用户跳题或者此题目不存在跳转错误页面
  if (isInQuestionRange === false) {
    history.push(`/questionAnswer/home/${questionnaireUuid}/closeResult`);
  }
};
